package com.xxl.job.admin.core.alarm.impl;

import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * MobileMessageJobAlarm
 *
 * @author crossice
 * @date 2020/5/21
 */
@Component
public class MobileMessageJobAlarm implements JobAlarm {

    private static Logger logger = LoggerFactory.getLogger(MobileMessageJobAlarm.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value("${xxl.alarm.phone.default}")
    private String defaultPhone;

    @Value("${xxl.alarm.sendMsg.url}")
    private String sendMsgUrl;

    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        boolean alarmResult = true;
        if (info != null && info.getAlarmPhone() != null && info.getAlarmPhone().trim().length() > 0) {

            String alarmContent = "“" + info.getJobDesc() + "”任务调度出错，beanName：" + info.getExecutorHandler() + "，请尽快登录http://api2.dam.com.cn:8080查看具体原因";
            Set<String> phoneSet = new HashSet<String>(Arrays.asList(info.getAlarmPhone().split(",")));
            MobileMessage mobileMessage = new MobileMessage();
            mobileMessage.setMessage(alarmContent);

            if (phoneSet == null || phoneSet.size() == 0) {
                phoneSet = new HashSet<String>(Arrays.asList(defaultPhone.split(",")));
            }

            ZonedDateTime zonedDateTime = ZonedDateTime.now();
            long offset = zonedDateTime.getOffset().getTotalSeconds() * 1000;
            long localTimestamp = zonedDateTime.toInstant().toEpochMilli() - offset;

            String secretKey = getMD5("interface_sms" + localTimestamp);

            String url = sendMsgUrl + "?secretKey=" + secretKey + "&timestamp=" + localTimestamp;

            phoneSet.forEach(phone -> {
                mobileMessage.setPhone(phone);
                HttpEntity<MobileMessage> request = new HttpEntity<>(mobileMessage);
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);

            });


        }

        return alarmResult;
    }

    public String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
